package com.thiscc.sum.service.impl;

import java.util.ArrayList;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.thiscc.sum.common.MongoDBManager;
import com.thiscc.sum.service.ISumService;
import com.thiscc.sum.utils.JSONUtils;

public class SumServiceImpl implements ISumService {
	//数据库操作对象
	private MongoDBManager db = MongoDBManager.getInstance();
	private String Summarize_reciever = "Summarize_reciever";
	@Override
	public String addReciever(String uuid, String name, String ccno,
			String recievers) {
		DBObject uuidBean = new BasicDBObject();
		uuidBean.put("uuid", uuid);
		DBObject bean = db.findOne(Summarize_reciever, uuidBean);
		
		if(bean == null){
			JSONArray recieverArray = JSONArray.fromObject(recievers);
			List<DBObject> reciever = new ArrayList<DBObject>();
			for (int i = 0; i < recieverArray.size(); i++) {
				JSONObject json = recieverArray.getJSONObject(i);
				DBObject dbo=new BasicDBObject();
				dbo.put("uuid", json.get("uuid"));
				dbo.put("ccno", json.get("ccno"));
				dbo.put("name", json.get("name"));
				reciever.add(dbo);
			}
			 //先删再插
			//db.delete(Summarize_reciever,new BasicDBObject("uuid",uuid));
			DBObject summary = new BasicDBObject();
			summary.put("uuid", uuid);
			summary.put("name", name);
			summary.put("ccno", ccno);
			summary.put("reciever", reciever);
			db.insert(Summarize_reciever, summary);
		}else{
			
			JSONArray recieverArray = JSONArray.fromObject(recievers);
			
			List<DBObject> addBeanList = new ArrayList<DBObject>();
			for(int i=0;i<recieverArray.size();i++){
				JSONObject temp = recieverArray.getJSONObject(i);
				DBObject addBean = new BasicDBObject();
				addBean.put("uuid", JSONUtils.getString(temp, "uuid"));
				addBean.put("ccno", JSONUtils.getString(temp, "ccno"));
				addBean.put("name", JSONUtils.getString(temp, "name"));
				addBeanList.add(addBean);
			}
			DBObject d = new BasicDBObject();
			d.put("reciever", addBeanList);
			db.update(Summarize_reciever, uuidBean, d);
		}
		return null;
	}
	
	@Override
	public String getReciever(String uuid) {
		DBObject condition = new BasicDBObject();
		condition.put("uuid", uuid);
		List<DBObject> dbs=db.find("Summarize_reciever", condition);
		JSONArray array=JSONArray.fromObject(dbs.get(0).get("reciever"));
		
		return array.toString();
	}

}
